const { JobModel, menuAndJobModel, doctorAndJobModel } = require("../model")

exports.addJob = async (req,res)=>{
    const { jName,jContent } = req.body
    //判断是否为空
    if(jName==null||jContent==null) {
        return res.status(400).json({
            code:400,
            message:"职位名称或内容不能为空",
            data:null
        })
    }
    let result = await JobModel.find({ jName })
  
    if(result.length>0) {
        return res.status(400).json({
            code:400,
            message:"职位名称重复",
            data:null
        })
    }
    const dbBack = new JobModel({
        jName,
        jContent
    })
    try {
        await dbBack.save()
        return res.status(200).json({
            code:200,
            message:"添加成功",
            data:null
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:"服务器出现问题，添加失败",
            data:null
        })
    }
}
///获取职位列表
exports.getJobList = async (req,res)=>{
    const {pageNo=1,pageSize=5} = req.query
    console.log(pageNo,pageSize);
    try {
        let result = await JobModel.find().skip((pageNo-1)*pageSize).limit(pageSize)
        //总条数
        let total = await JobModel.find().count()
        res.status(200).json({
            code:200,
            message:"获取成功",
            data:result,
            total
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:"获取失败",
            data:error,
          
        })
    }
}
//添加菜单权限给职位
exports.addMenuToJob = async (req,res)=>{
    const { jid,mids } = req.body
    if(jid==null||mids==null) {
        return res.status(400).json({
            code:400,
            message:"职位id或菜单id不能为空",
            data:null
            
        })
    }
    let result = await menuAndJobModel.find({jid:jid})
    if(result.length>0) {
        req.query.id = jid
        return this.updateJob(req,res)
    }
  try {
    for(let i=0;i<mids.length;i++) {
        //添加之前先判断是否存在
        let result = await menuAndJobModel.find({ jid,mid:mids[i] })
        if(result.length>0) {
            return res.status(400).json({
                code:400,
                message:"该职位已存在该菜单",
                data:null
                
            })
        }
        let dbBack = new menuAndJobModel({
            jid,
            mid:mids[i]
        })
       await dbBack.save()
    }
    res.status(200).json({
        code:200,
        message:"添加成功",
        data:null
    })
  } catch (error) {
    res.status(500).json({
        code:500,
        message:"添加失败",
        data:null
    })
  }
}
//获取职位详情
exports.getJobDetail = async (req,res)=>{
    const {id} = req.query
    if(id==null) {
        return res.status(400).json({
            code:400,
            message:"id不能为空",
            data:null
        })
    }
    try {
        let result = await JobModel.findById(id)
        let result2 = await menuAndJobModel.find({ jid:id }).populate("jid","_id jName jContent").populate("mid","_id mName")
        if(result==null) {
            return res.status(400).json({
                code:400,
                message:"该职位不存在",
                data:null
            })
        }
        let menus = result2.map(item=>{
            return {
                _id:item._id,
                menuId:item.mid._id,
                menuName:item.mid.mName
            }
        })
        let data = {
            jid:result._id,
            jName:result.jName,
            jContent:result.jContent,
            menus:menus
        }
        res.status(200).json({
            code:200,
            message:"获取成功",
            data:data
            
        })
    }catch(err) {
        res.status(500).json({
            code:500,
            message:"获取失败",
            data:err
        })
    }
}
//修改职位
exports.updateJob = async (req, res) => {  
    const { id } = req.query;  
    const { mids } = req.body;  
  
    try {  
        // 删除所有字段为id的  
        await menuAndJobModel.deleteMany({ jid: id });  
  
        // 添加新的  
        const newRecords = [];  
        for (let i = 0; i < mids.length; i++) {  
            let dbBack = new menuAndJobModel({  
                jid: id,  
                mid: mids[i]  
            });  
            const savedRecord = await dbBack.save();  
            newRecords.push(savedRecord); // 保存新添加的记录  
        }  
  
        // 发送一次响应  
        res.status(200).json({  
            code: 200,  
            message: "修改成功",  
            data: newRecords // 可以返回新添加的记录详情  
        });  
    } catch (error) {  
        console.error('Error updating job:', error); // 记录错误详情  
        res.status(500).json({  
            code: 500,  
            message: "修改失败",  
            data: null  
        });  
    }  
};
//删除职位
exports.deleteJob = async (req,res)=>{
    const {id} = req.query
    if(id==null) {
        return res.status(400).json({
            code:400,
            message:"id不能为空",
            data:null
        })
    }
    let isJob = await doctorAndJobModel.find({ jid:id })
    if(isJob.length>0) {
        return res.status(400).json({
            code:400,
            message:"该职位下存在医生，无法删除",
            data:null 
        })
    }
    try {
        await JobModel.deleteOne({ _id: id });
        await menuAndJobModel.deleteMany({ jid: id });
        res.status(200).json({
            code:200,
            message:"删除成功",
            data:null
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:"删除失败",
            data:error
        })
    }
}
//修改职位信息
exports.updateJobName = async (req,res)=>{
    const id = req.query.id
    const {jName,jContent} = req.body
    if(id==null||jName==null||jContent==null) {
        return res.status(400).json({
            code:400,
            message:"关键信息不能为空",
            data:null
        })
    }
    try {
        await JobModel.updateOne({_id:id},{jName,jContent})
        res.status(200).json({
            code:200,
            message:"修改成功",
            data:null
        })
    } catch (error) {
        res.status(500).json({
            code:500,
            message:"修改失败",
            data:null
        })
    }
}